<template>
  <div class="interaction-matrix">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>组件相互作用力分析矩阵</span>
          <div>
            <el-switch
              v-model="editable"
              active-text="编辑模式"
              inactive-text="查看模式"
              style="margin-right: 10px;"
            />
            <el-button :type="editable ? 'primary' : 'default'" @click="handleSave" :loading="loading" :disabled="!editable">
              保存关系
            </el-button>
          </div>
        </div>
      </template>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <!-- 矩阵表格 -->
      <div v-else-if="componentList.length > 0 && matrixInitialized" class="matrix-container">
        <table class="interaction-table">
          <thead>
            <tr>
              <th class="corner-cell">作用力方向 →<br/>被作用组件 ↓</th>
              <th v-for="component in componentList" :key="'header-' + component.id" class="header-cell" >
                {{ component.name }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(rowComponent, rowIndex) in componentList" :key="'row-' + rowComponent.id">
              <td class="row-header-cell">{{ rowComponent.name }}</td>
              <td 
                v-for="(colComponent, colIndex) in componentList" 
                :key="'cell-' + rowComponent.id + '-' + colComponent.id"
                class="interaction-cell"
                :class="{ 'self-cell': rowComponent.id === colComponent.id }"
              >
                <template v-if="rowComponent.id === colComponent.id">
                  <!-- 自身单元格，显示为空 -->
                  <span class="self-text">-</span>
                </template>
                <template v-else>
                  <!-- 交互单元格 -->
                  <template v-if="editable">
                    <el-select
                      v-model="matrixData[rowIndex][colIndex]"
                      @change="handleInteractionChange(rowComponent.id, colComponent.id, $event)"
                      size="small"
                      class="interaction-select"
                      placeholder="请选择"
                    >
                      <el-option label="" value=""></el-option>
                      <el-option label="有直接接触 (+)" value="+"></el-option>
                      <el-option label="无直接接触 (-)" value="-"></el-option>
                    </el-select>
                  </template>
                  <template v-else>
                    <span 
                      v-if="matrixData[rowIndex] && matrixData[rowIndex][colIndex] !== undefined"
                      class="interaction-display" 
                      :class="getInteractionClass(matrixData[rowIndex][colIndex])"
                    >
                      {{ getInteractionDisplay(matrixData[rowIndex][colIndex]) }}
                    </span>
                    <span v-else class="interaction-display interaction-none">无</span>
                  </template>
                </template>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 图例说明 -->
        <div class="legend">
          <div class="legend-item">
            <span class="legend-color positive"></span>
            <span>有直接接触 (+)</span>
          </div>
          <div class="legend-item">
            <span class="legend-color negative"></span>
            <span>无直接接触 (-)</span>
          </div>
          <div class="legend-item">
            <span class="legend-color none"></span>
            <span>无作用力</span>
          </div>
        </div>
      </div>

      <div v-else-if="!loading" class="empty-state">
        <el-empty description="暂无组件数据" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { listComponentAnalysis } from "@/api/business/componentAnalysis"
import { listComponentInteraction, saveInteractionRelations, updateComponentInteraction } from "@/api/business/componentInteraction"
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import store from "@/store"



const userName = store.state.value.user.name;//当前登陆用户
const route = useRoute()

// 响应式数据
const componentList = ref([])
const componentInteractionList = ref([]) // 组件相互作用关系
const matrixData = ref([])
const matrixInitialized = ref(false) // 矩阵是否已初始化
const editable = ref(false) // 默认查看模式
const loading = ref(false)

// 处理交互关系变化
const handleInteractionChange = (sourceId, targetId, interactionType) => {
  // console.log(`组件 ${sourceId} -> ${targetId}: ${interactionType}`)
}

// 获取交互显示文本
const getInteractionDisplay = (type) => {
  const map = {'+': '+', '-': '-' }
  return map[type] || ''
}

// 获取交互样式类
const getInteractionClass = (type) => {
  return {
    'interaction-positive': type === '+',
    'interaction-negative': type === '-',
    'interaction-none': type === '' || !type
  }
}

// 安全获取矩阵值
const getMatrixValue = (rowIndex, colIndex) => {
  if (!matrixData.value[rowIndex] || matrixData.value[rowIndex][colIndex] === undefined) {
    return ''
  }
  return matrixData.value[rowIndex][colIndex]
}

// 构建保存数据
const buildSaveData = () => {
  const relations = []
  componentList.value.forEach((rowComponent, rowIndex) => {
    componentList.value.forEach((colComponent, colIndex) => {
      if (rowComponent.id !== colComponent.id) {
        const interactionType = getMatrixValue(rowIndex, colIndex)
        if (interactionType && interactionType.trim() !== '') {
          relations.push({
            projectId: route.query.id, // 项目id
            sourceId: rowComponent.id,
            targetId: colComponent.id,
            interactionType: interactionType,
						createBy: userName,
          })
        }
      }
    })
  })
  return relations
}

// 保存数据
const handleSave = async () => {
  if (!editable.value) {
    ElMessage.warning('请切换到编辑模式进行修改')
    return
  }

  loading.value = true
  try {
    const relations = buildSaveData()
    
    // 调用API保存
    await saveInteractionRelations(relations)
    
    ElMessage.success('相互作用力关系保存成功')
    editable.value = false // 保存后切换到查看模式
    
    // 重新加载数据以确保一致性
    await loadData()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 初始化矩阵数据
const initializeMatrix = () => {
  const n = componentList.value.length
  console.log('初始化矩阵，组件数量:', n)
  
  // 安全地创建 n x n 矩阵
  matrixData.value = Array.from({ length: n }, () => Array.from({ length: n }, () => ''))
  
  // 填充相互作用力关系数据
  if (componentInteractionList.value.length > 0) {
    componentInteractionList.value.forEach(relation => {
      const sourceIndex = componentList.value.findIndex(comp => comp.id === relation.sourceId)
      const targetIndex = componentList.value.findIndex(comp => comp.id === relation.targetId)
      
      if (sourceIndex !== -1 && targetIndex !== -1) {
        // 确保矩阵行存在
        if (!matrixData.value[sourceIndex]) {
          matrixData.value[sourceIndex] = []
        }
        matrixData.value[sourceIndex][targetIndex] = relation.interactionType || ''
      } else {
        console.warn(`未找到对应的组件索引: sourceId=${relation.sourceId}, targetId=${relation.targetId}`)
      }
    })
  }
  
  matrixInitialized.value = true
  console.log('矩阵初始化完成:', matrixData.value)
}

// 加载组件列表和关系数据
const loadData = async () => {
  loading.value = true
  matrixInitialized.value = false
  
  try {
    const queryParams = {
      pageNum: 1,
      pageSize: 1000,
      projectId: route.query.id,
    }
    
    // 加载组件列表
    const response = await listComponentAnalysis(queryParams)
    componentList.value = response.rows || []
    
    // 加载相互作用力关系数据
    const interactionResponse = await listComponentInteraction(queryParams)
    componentInteractionList.value = interactionResponse.rows || []
    
    // 初始化矩阵
    initializeMatrix()
    
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 监听编辑模式变化
watch(editable, (newVal) => {
  if (newVal) {
    ElMessage.info('已进入编辑模式，可以修改相互作用力关系')
  }
})

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.interaction-matrix {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 20px;
}

.matrix-container {
  overflow-x: auto;
  margin: 20px 0;
}

.interaction-table {
  width: auto;
  min-width: 100%;
  border-collapse: collapse;
  border: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.interaction-table th,
.interaction-table td {
  border: 1px solid #ebeef5;
  padding: 12px;
  text-align: center;
  min-width: 120px;
}

.corner-cell {
  background: #f5f7fa;
  font-weight: bold;
  min-width: 150px;
}

.header-cell {
  background: #409eff;
  color: white;
  font-weight: bold;
  white-space: nowrap;
}

.row-header-cell {
  background: #f5f7fa;
  font-weight: bold;
  white-space: nowrap;
}

.self-cell {
  background: #f0f0f0;
}

.interaction-cell {
  background: white;
  height: 60px;
}

.self-text {
  color: #c0c4cc;
  font-style: italic;
}

.interaction-select {
  width: 120px;
}

.interaction-display {
  font-weight: bold;
  font-size: 16px;
  padding: 8px 12px;
  border-radius: 4px;
  display: inline-block;
  min-width: 40px;
}

.interaction-positive {
  background-color: #f0f9ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.interaction-negative {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.interaction-none {
/*  background-color: #fafafa;
  color: #999;
  border: 1px solid #d9d9d9; */
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.legend {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.legend-color.positive {
  background-color: #f0f9ff;
  border-color: #91d5ff;
}

.legend-color.negative {
  background-color: #fff2f0;
  border-color: #ffccc7;
}

.legend-color.none {
  background-color: #fafafa;
  border-color: #d9d9d9;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .interaction-matrix {
    padding: 10px;
  }
  
  .matrix-container {
    font-size: 12px;
  }
  
  .interaction-table th,
  .interaction-table td {
    padding: 8px 4px;
    min-width: 80px;
  }
  
  .legend {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
}
</style>